package io.p2p.stream.p2pmain.handler;

import com.alibaba.fastjson.JSONObject;
import common.core.domain.udp.UdpApiProtocol;
import io.netty.buffer.Unpooled;
import io.netty.channel.socket.DatagramPacket;
import io.p2p.stream.p2pmain.session.ActiveNodeSessionManager;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;

/**
 * 登录协议类
 */
@Slf4j
public class ClientLoginHandler {
   private UdpApiProtocol apiProtocol;

   public ClientLoginHandler(UdpApiProtocol apiProtocol) {
       this.apiProtocol = apiProtocol;
   }

   public void login() {

       String loginName = apiProtocol.getBuffer().getString("name");

       String clientIp = apiProtocol.getRemoteIP();
       int clientPort = apiProtocol.getRemotePort();

       if(ActiveNodeSessionManager.getInstance().find(loginName) != null){
           log.info("User name: {} already exists login failed.",loginName);
           //发送登录应答指令给客户端
           JSONObject ack = new JSONObject();
           ack.put("type","loginAck");
           ack.put("success","false");
           String msg = String.format("User name: %s already exists login failed.",loginName);
           ack.put("msg",msg);

           apiProtocol.getCtx().writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(
                   ack.toJSONString(), StandardCharsets.UTF_8), new InetSocketAddress(clientIp,clientPort)));
       }else{
           //刷新节点
           ActiveNodeSessionManager.getInstance().flush(loginName,clientIp,clientPort);

           log.info("Client at IP: {},Port: {},Name: {} is online.",clientIp,clientPort,loginName);

           //发送登录应答指令给客户端
           JSONObject ack = new JSONObject();
           ack.put("type","loginAck");
           ack.put("success","true");
           String msg = String.format("Client at IP: %s,Port: %s,Name: %s is online.",clientIp,clientPort,loginName);
           ack.put("msg",msg);

           apiProtocol.getCtx().writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(
                   ack.toJSONString(), StandardCharsets.UTF_8), new InetSocketAddress(clientIp,clientPort)));

       }
   }
}
